// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const { applicationId, action } = event

  try {
    // 检查申请是否存在
    const { data: applications } = await db.collection('applications')
      .where({
        _id: applicationId,
        status: 'pending'
      })
      .get()

    if (applications.length === 0) {
      return {
        success: false,
        message: '申请不存在或已处理'
      }
    }

    // 更新申请状态
    const result = await db.collection('applications').doc(applicationId).update({
      data: {
        status: action === 'approve' ? 'approved' : 'rejected',
        approveTime: db.serverDate()
      }
    })

    return {
      success: true,
      message: action === 'approve' ? '已批准' : '已拒绝'
    }

  } catch (error) {
    console.error(error)
    return {
      success: false,
      message: '操作失败，请重试'
    }
  }
} 